import { useRef } from 'react'
import store from '../../redux/store'
import {
    createIncrementAction,
    createDecrementAction,
    createAsyncInreacementAction
 } from "../../redux/counter_action"


export const CompletedReduxCounterComponent = () => {

    const selectRef = useRef()

    const onIncreacementBtnClicked = () => {
        const { value: step } = selectRef.current
        // 派发 action 触发 reducer 以更新状态
        store.dispatch(createIncrementAction(step))
    }
    const onSubtractionBtnClicked = () => {
        const { value: step } = selectRef.current
        store.dispatch(createDecrementAction(step))
    }
    const onIncreaceIfEvenBtnClicked = () => {
        // 使用 store.getState() 直接获取到 store 内存储的值
        const result = store.getState()
        const { value: step } = selectRef.current
        if (!(result % 2)) {
            store.dispatch(createIncrementAction(step))
        }

    }
    const onAsyncIncreacementBtnClicked = () => {
        const { value: step } = selectRef.current
        // setTimeout(() => {
        //     store.dispatch(createIncrementAction(step))
        // }, 1500)
        store.dispatch(createAsyncInreacementAction(step, 1000))
    }

    return (
        <>
            <h3>当前和为：{store.getState()}</h3>
            <select ref={selectRef}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>&nbsp;
            <button onClick={onIncreacementBtnClicked}>加！</button>&nbsp;
            <button onClick={onSubtractionBtnClicked}>减！</button>&nbsp;
            <button onClick={onIncreaceIfEvenBtnClicked}>偶数再加！</button>&nbsp;
            <button onClick={onAsyncIncreacementBtnClicked}>等会儿加！</button>
        </>
    )
}